<?php

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport('joomla.application.component.model');

class SyncrModelContent extends JModel
{
	function __construct() {
		parent::__construct();
		
		// new class
		$evl = new evolveLibrary;
		
		// load some evl stuff
		$this->_log = $evl->loadHelper('log');
	}
	
	public function getData()
	{
		
	
		// Lets load the content if it doesn't already exist
		if (empty($this->_data))
		{	
		
			if (!JRequest::getInt('categoryId', 0)) {
				$this->_log->simpleLog('content.php/getData: no category specified', 'syncr');
				
				JError::raiseError(412, JText::_('No category specified'));
			}
			
			if (JRequest::getVar('categoryId') == '-1') {
				$this->_data = $this->_buildFlagQuery();
			} else {
				$this->_data = $this->_buildQuery();
			}
		}
		
		if (is_array($this->_data)) {
			return json_encode($this->_data);
		}
	}
	
	private function _buildQuery()
	{	
		$db = &JFactory::getDBO();
		
		$query = 'SELECT c.id'
			  .', c.title'
			   .' FROM #__content AS c'
			   .$this->_buildWhere()
			   .' ORDER BY title ASC'
			   ;
		
		$db->setQuery($query);
		$results = $db->loadAssocList();
		
		if (!count($results)) {
			$this->_log->simpleLog('content.php/_buildQuery: could not find content', 'syncr');
			
			JError::raiseNotice(204, JText::_('Could not find content'));
		}
		
		return $results;
	}
	
	private function _buildWhere($flags = false)
	{
		$params = &JComponentHelper::getParams( 'com_syncr' );
		
		$where = null;
		if ($published_only = $params->get('published_only')) {
			$where[] = 'c.state = 1';
		}
		
		if (!$flags) {
			if (!$categoryId = JRequest::getVar('categoryId', 0)) {
				$this->_log->simpleLog('content.php/_buildWhere: no category selected', 'syncr');
			
				JError::raiseError(416, JText::_('No category selected'));
			}
			
			if ($categoryId != -2) {
				$where[] = 'c.catid = '. $categoryId;
			}
			
			$where[] = 'c.checked_out = 0';
		}
		
		if ($flags) {
			$where[] = 'f.published = 1';
		}
		
		if (count($where)) {
			return ' WHERE ' . implode(' AND ', $where);
		}
		
		return;
	}
	
	private function _buildFlagQuery()
	{
		$db = &JFactory::getDBO();
		
		$query = 'SELECT f.content_id AS id'
			   .', c.title'
			   .' FROM #__syncr_flags AS f'
			   .' LEFT JOIN #__content AS c ON c.id = f.content_id'
			   .  $this->_buildWhere(true)
			   .' ORDER BY c.title ASC'
			   ;
			   
		$db->setQuery($query);
		$results = $db->loadAssocList();
		
		if (!count($results)) {
			$this->_log->simpleLog('content.php/_buildFlagQuery: could not find content', 'syncr');
		
			JError::raiseNotice(204, JText::_('Could not find content'));
		}
		
		return $results;
	}
}